package com.shuang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shuang.mapper.ClazzMapper;
import com.shuang.pojo.Clazz;
import com.shuang.pojo.ClazzQueryParam;
import com.shuang.pojo.PageResult;
import com.shuang.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    /*班级分页查询*/
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {

//        设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());

//        执行查询
        List<Clazz> clazzList = clazzMapper.page(clazzQueryParam);

        //设置班级状态
        for (Clazz clazz : clazzList) {
            //开课时间
            LocalDate beginDate = clazz.getBeginDate();
//            结课时间
            LocalDate endDate = clazz.getEndDate();
//            当前时间
            LocalDate now = LocalDate.now();
            if (now.isAfter(endDate)){
                clazz.setStatus("已结课");
            }else if (now.isBefore(beginDate)){
                clazz.setStatus("未开班");
            }else {
                clazz.setStatus("在读中");
            }
        }

        Page<Clazz> clazzPage = (Page<Clazz>) clazzList;

        return new PageResult<Clazz>(clazzPage.getTotal(), clazzPage.getResult());
    }

    /*新增班级信息*/
    @Override
    public void save(Clazz clazz) {
        //1 补全基本属性
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        //2 增加班级
        clazzMapper.save(clazz);
    }

    /*根据班级id查询回显*/
    @Override
    public Clazz getInfo(Integer id) {
        return clazzMapper.getInfo(id);
    }

    /*更新班级信息*/
    @Override
    public void update(Clazz clazz) {
        //1 补全基本属性
        clazz.setUpdateTime(LocalDateTime.now());
        //2
        clazzMapper.update(clazz);
    }

    /*删除班级*/
    @Override
    public void delete(Integer id) {
        //先查询班级里是否有学员如果有不允许删除 抛一个自定义异常让全局异常处理捕获到响应给前端信息
        //得到班级学员人数
        Integer num = clazzMapper.getClazzStudentNum(id);

        if (num==0){
            clazzMapper.delete(id);
        }else {
            int i = 1/0; //自定义一个除零异常
        }
    }

    /*查询所有班级*/
    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }
}
